package com.nhn.ssi.client;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

import com.nhn.ssi.bean.Product;
import com.nhn.ssi.util.FilePathUtil;

/**
 * author lighter date 2006-8-7
 */
public class DBIndexerGRTClient {
	public static void main(String[] args) throws Exception {
		List<Product> list = ClientUtil.getProductList();

		/* 这里放索引文件的位置 */
		File indexDir = new File(FilePathUtil.INDEX_FILE_DIR);
		Analyzer luceneAnalyzer = new StandardAnalyzer();
		IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer, true);
		long startTime = new Date().getTime();

		// 增加document到索引去
		for (Product pdt : list) {
			System.out.println("record " + pdt.getId() + "正在被索引....");
			Document document = new Document();
			String merchant = "";
			Field fieldMerchant = new Field("merchant", pdt.getDescription(), Field.Store.YES, Field.Index.TOKENIZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);
			Field fieldName = new Field("name", pdt.getName(), Field.Store.YES, Field.Index.TOKENIZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);
			Field fieldDSPT = new Field("description", pdt.getDescription(), Field.Store.YES, Field.Index.TOKENIZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);
			Field fieldADDDSPT = new Field("additional_description", pdt.getAdditional_description(), Field.Store.YES,
				Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
			Field fieldPrice = new Field("price", pdt.getPrice(), Field.Store.YES, Field.Index.TOKENIZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);
			Field fieldSpecialPrice = new Field("special_price", pdt.getSpecial_price(), Field.Store.YES,
				Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
			String salePrice = (Double.parseDouble(pdt.getPrice()) - Double.parseDouble(pdt.getSpecial_price())) + "";
			Field fieldSalePrice = new Field("sale_price", salePrice, Field.Store.YES, Field.Index.TOKENIZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);

			document.add(fieldName);
			document.add(fieldDSPT);
			document.add(fieldADDDSPT);
			document.add(fieldPrice);
			document.add(fieldSpecialPrice);
			document.add(fieldSalePrice);

			indexWriter.addDocument(document);
		}

		// optimize()方法是对索引进行优化
		indexWriter.optimize();
		indexWriter.close();

		// 测试一下索引的时间
		long endTime = new Date().getTime();
		System.out.println("这花费了" + (endTime - startTime) / 1000 + " 秒来把文档增加到索引里面去!");
	}
}